package br.com.medvagas.web.conversor;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang.StringUtils;

@FacesConverter("conversorCEP")
public class ConversorCEP implements Converter {
	
	@Override
	public String getAsString(FacesContext FacesContext, UIComponent UIComponent, Object valor) 
			throws ConverterException {
		
		String valorString = (String) valor;
		
		if (StringUtils.isNotEmpty(valorString) && valorString.length() == 8) {
			return valorString.substring(0, 2) + "." + valorString.substring(2, 5) + "-" + valorString.substring(5);
		}
		
		return valorString;
	}

	@Override
	public Object getAsObject(FacesContext FacesContext, UIComponent UIComponent, String valor) 
			throws ConverterException {

		return valor != null ? valor.replaceAll("-", "").replaceAll("\\.", "") : null;
	}

}
